import time
import requests
import os
import jenkins

project_name = os.environ.get('PROJECT_NAME')
jenkins_url = os.environ.get('JENKINS_URL')
job_url = os.environ.get('JOB_URL')
job_name = os.environ.get('JOB_NAME')
build_id = os.environ.get('BUILD_ID')
# build_status = os.environ.get('BUILD_STATUS')
cur_build_end_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
# 飞书webhook
webhook = 'https://open.feishu.cn/open-apis/bot/v2/hook/b958b58a-a3dc-4a42-82a2-b4da64c32f8a'
# 建立jenkins连接
jk = jenkins.Jenkins(url=jenkins_url, username='gcat255', password='11ca98bd9cc11cb7cd8b4113abc52d6fff') # 需修改对应jenkins账户与令牌

method = 'post'
                
def sendBuildEndMsg():
        headers = {
                'Content-Type': 'application/json'
        }       
        jsonData = {
                "msg_type": "interactive",
                "card": {
                        "config":{
                        "enable_forward": True,
                        "width_mode": "fill",
                        },
                        "elements": [{
                                "tag": "div",
                                "text": {
                                        "content": '任务名称：**'+ job_name +'**\n构建编号: '+ build_id +'\nUnity构建项目名称: '+ project_name + '\n构建状态: '+ build_result +'\n构建结束时间: '+ cur_build_end_time +'',
                                        "tag": "lark_md"
                                }
                        }],
                        "header": {
                                "title": {
                                        "content": 'LCM自动构建报告',
                                        "tag": "plain_text"
                                }
                        }
                }
        }
        upload_build_log()

        print('构建结果: ' + build_result)
        # 发送飞书机器人消息请求
        requests.request(method=method, url=webhook, headers=headers, json=jsonData)

def upload_build_log():
       if build_result == '构建失败！' or code_error != None :
               # 创建Jenkins Log文件，并写入
               fileName = 'jenkins_log.txt'
               filePath = './jenkins_log.txt'
               file = open(file=filePath, mode='w')
               file.write(build_log)
               form = {
                      'file_type': 'stream',
                        'file_name': fileName,
                        'file':  (fileName, open(filePath, 'rb'), 'text/plain')
               }
               log_headers = {
                      'Content-Type': 'multipart/form-data; boundary=---7MA4YWxkTrZu0gW'
               }
               requests.request(method=method, url='https://open.feishu.cn/open-apis/im/v1/files', headers=log_headers, json=form)

if __name__ == '__main__':
        build_result = jk.get_build_info(name=job_name, number=build_id)['result']
        build_log = jk.get_build_console_output(name=job_name, number=build_id)
        if build_result == 'SUCCESS':
              build_result = '构建成功！'
        elif build_result == 'FAILURE':
              build_result = '构建失败！'

        # 代码错误时
        # code_error = os.environ.get('CODE_ERROR')
        # if code_error != None:
        #        build_result = code_error
        sendBuildEndMsg()

